package com.example.tests;

import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.openqa.selenium.support.ui.ExpectedConditions.alertIsPresent;
import org.openqa.selenium.*;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.example.pages.InternalPage;
import com.example.pages.LoginPage;
import com.example.pages.UserManagmentPage;

import ru.esteru.selenium.factory.WebDriverFactory;

public class CreateNewUserTest {
  private WebDriver driver;
  private WebDriverWait wait;
  private String baseUrl;
  private StringBuffer verificationErrors = new StringBuffer();
  private LoginPage loginPage;
  private InternalPage somePage;
  private UserManagmentPage userManagmentPage;

  @Before
  public void setUp() throws Exception {
	driver = WebDriverFactory.getDriver(DesiredCapabilities.firefox());
    baseUrl = "http://localhost/";
    wait = new WebDriverWait(driver, 10);
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
  }

  @Test
  public void testUntitled() throws Exception {
    goToHomePage();
    loginAs("admin", "admin");
    openUserManagmentPage();
    createNewUser("NewUser", "NewUser@example.com", "123");
    logout();
    loginAs("NewUser", "123");
    logout();
  }

private void logout() {
	somePage.menuLogoutLink.click();
	wait.until(alertIsPresent()).accept();
}

private void createNewUser(String username, String useremail, String userpass) {
	userManagmentPage.usernameField.clear();
	userManagmentPage.usernameField.sendKeys(username);
	userManagmentPage.emailField.clear();
	userManagmentPage.emailField.sendKeys(useremail);
	userManagmentPage.passwordField.clear();
	userManagmentPage.passwordField.sendKeys(userpass);
	userManagmentPage.password2Field.clear();
	userManagmentPage.password2Field.sendKeys(userpass);
	userManagmentPage.submitButtonField.click();
}

private void openUserManagmentPage() {
	somePage.menuManagementLink.click();
}

private void loginAs(String username, String password) {
	loginPage.userNameField.clear();
    loginPage.userNameField.sendKeys(username);
    loginPage.passwordField.clear();
    loginPage.passwordField.sendKeys(password);
    loginPage.loginButton.click();
}

private void goToHomePage() {
	driver.get(baseUrl + "php4dvd/");
	loginPage = PageFactory.initElements(driver, LoginPage.class);
	somePage = PageFactory.initElements(driver, InternalPage.class);
	userManagmentPage = PageFactory.initElements(driver, UserManagmentPage.class);
}

  @After
  public void tearDown() throws Exception {
    driver.quit();
    String verificationErrorString = verificationErrors.toString();
    if (!"".equals(verificationErrorString)) {
      fail(verificationErrorString);
    }
  }
}
